package com.dino.manager.clients;

import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.form.SubmitLink;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;

import com.dino.manager.AbstractPage;
import com.test.clients.dto.Client;
import com.test.clients.service.ClientsService;

public class EditClient extends AbstractPage {

	/**
	 * Generated serial version UID.
	 */
	private static final long serialVersionUID = -8118034280290728420L;

	@SpringBean
	private ClientsService clientService;

	private final Client editedClient;

	public EditClient() {
		this(new Client());
	}

	public EditClient(final int clientId) {
		this.editedClient = clientService.getClientById(clientId);
		init();
	}

	private EditClient(final Client editedClient) {
		this.editedClient = editedClient;
		init();
	}

	private void init() {
		add(new EditClientForm("editClientForm", editedClient, clientService));
	}

	private class EditClientForm extends Form<Client> {

		/**
		 * Generated serial version UID.
		 */
		private static final long serialVersionUID = 8436231805765591338L;

		private final CompoundPropertyModel<Client> model;

		private final ClientsService service;

		public EditClientForm(final String id, final Client editedClient, final ClientsService service) {
			super(id);
			this.service = service;
			model = new CompoundPropertyModel<Client>(editedClient);
			setModel(model);
			add(new Label("clientId", editedClient.getId() <= 0 ? "new client" : editedClient.getId() + ""));
			add(new RequiredTextField<String>("name"));
			add(new FormSubmitLink("save"));
		}

		private class FormSubmitLink extends SubmitLink {

			public FormSubmitLink(String id) {
				super(id);
			}
			
			/**
			 * Generated serial version UID.
			 */
			private static final long serialVersionUID = 1167210624196924656L;

			@Override
			public void onSubmit() {
				if (model.getObject().getId() <= 0) {
					service.addClient(model.getObject());
				} else {
					service.updateClient(model.getObject());
				}
				setResponsePage(ClientSearch.class);
			}
		}
		
	}
}
